package com.mindata.blockmanager.controller.admin;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Controller
@Slf4j
public class HomeController extends BaseController {

    @RequestMapping("/turnTo/{pageName}")
    public ModelAndView turnTo(@PathVariable("pageName") String pageName) {
        log.info("pageName....{}", pageName);
        return new ModelAndView(pageName);
    }

    @RequestMapping("/turnTo/{module}/{pageName}")
    public ModelAndView turnTo(@PathVariable("module") String module,
                               @PathVariable("pageName") String pageName) {
        String url = String.format("%s/%s", module, pageName);
        log.info("pageName...." + url);
        return new ModelAndView(url);
    }


    @RequestMapping({"/", "/index"})
    public ModelAndView index(ModelAndView mv) {
        mv.setViewName("index");
        mv.addObject("swagger_url", "http://172.16.185.136:8089/swagger-ui.html");
        return mv;
    }

    @RequestMapping("/login")
    public ModelAndView login(HttpServletRequest request, ModelAndView mv) {
        if (super.isLogin()) {
            return new ModelAndView("index");
        }

        // 登录失败从request中获取shiro处理的异常信息。
        // shiroLoginFailure:就是shiro异常类的全类名.
        String exception = (String) request.getAttribute("shiroLoginFailure");
        String msg = "";
        if (exception != null) {
            if (UnknownAccountException.class.getName().equals(exception)) {
                msg = "账号不存在";
            } else if (IncorrectCredentialsException.class.getName().equals(exception)) {
                msg = "密码不正确";
            } else if ("kaptchaValidateFailed".equals(exception)) {
                msg = "验证码错误";
            } else {
                msg = exception;
            }
            log.error("login error:{}", msg);
        }
        mv.addObject("msg", msg);
        mv.setViewName("login");
        return mv;
    }

    @RequestMapping("/403")
    public ModelAndView unauthorizedRole() {
        return new ModelAndView("403");
    }

}